import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';

// 扩展 Axios 配置类型
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
    retry?: number; // 自定义重试属性
    __retryCount?: number; // 内部重试计数属性
}

const http: AxiosInstance = axios.create({
    baseURL: 'http://localhost:64001',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json',
    },
});

const retryCount = 3;
const retryDelay = 1000; // 每次重试之间的延迟时间

// 请求拦截器
http.interceptors.request.use(
    (config: CustomAxiosRequestConfig) => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error: AxiosError) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
http.interceptors.response.use(
    (response: AxiosResponse) => {
        return response.data;
    },
    (error: AxiosError) => {
        const config = error.config as CustomAxiosRequestConfig;
        if (!config || config.__retryCount === undefined) return Promise.reject(error);

        config.__retryCount = config.__retryCount || 0;

        if (config.__retryCount >= (config.retry || retryCount)) {
            return Promise.reject(error);
        }

        config.__retryCount += 1;

        const backoff = new Promise<void>((resolve) => {
            setTimeout(() => {
                resolve();
            }, retryDelay);
        });

        return backoff.then(() => http(config));
    }
);

export default http;
